package com.lagou.server;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ServerComunicator extends Thread {
    private Socket s;
    PrintStream ps;

    private ObjectInputStream ois/* = null*/;
    private ObjectOutputStream oos/* = null*/;

    private boolean runFlag = true;

    /*// 数据相关
    private ServerDao sd;
    // 视图相关
    private ServerView sv;*/


    public ObjectInputStream getOis() {
        return ois;
    }

    public ObjectOutputStream getOos() {
        return oos;
    }
    public PrintStream getPs() {
        return ps;
    }

    public String getAddressInfo() {
        StringBuilder builder = new StringBuilder();
        return builder.append(s.getInetAddress()).append(s.getPort()).toString();
    }


    public ServerComunicator(Socket s) {
        this.s = s;
        try {
            ps = new PrintStream(s.getOutputStream());
            // 3.使用输入输出流进行通信
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null == ps) {
                System.out.println("创建打印流失败！");
            }
        }
    }

    // 自定义不断，等待客户端消息的线程。处理完之后，通知回复给客户端
    @Override
    public void run() {
        try {

            while(runFlag) {
                // 实现对客户端发来字符串内容的接收并打印
                // 当没有数据发来时，下面的方法会形成阻塞
                System.out.println("客户端" + getAddressInfo() + "发来消息");

                // 根据发过来是数据，处理相应消息，然后返回
                try {
                    ServerView.getInstance().serverReceive(this);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != ps) {
                ps.close();
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void closeServerCommunicateThread() throws IOException, InterruptedException {
        runFlag = false;
        this.join(500);
        oos.close();
        ois.close();
        s.close();
    }
}
